package com.daikit.daikit4gxt.client.ui.columnconfig;

import com.daikit.daikit4gxt.client.action.DkBaseAction;
import com.daikit.daikit4gxt.client.ui.cell.IconButtonCell;
import com.daikit.daikit4gxt.client.ui.cell.ListStoreIconButtonCell;
import com.google.gwt.resources.client.ImageResource;
import com.sencha.gxt.core.client.ValueProvider;
import com.sencha.gxt.data.shared.ListStore;
import com.sencha.gxt.widget.core.client.grid.ColumnConfig;


/**
 * Column config for action
 *
 * @author tcaselli
 * @version $Revision$ Last modifier: $Author$ Last commit: $Date$
 * @param <MODEL_TYPE>
 * @param <ACTION_RETURN_TYPE>
 */
public abstract class DkRunActionColumnConfig<MODEL_TYPE, ACTION_RETURN_TYPE> extends ColumnConfig<MODEL_TYPE, String>
{

	/**
	 * Constructor
	 *
	 * @param valueProvider
	 * @param icon
	 * @param tooltip
	 * @param actionLoadingLabel
	 * @param listStore
	 */
	public DkRunActionColumnConfig(final ValueProvider<? super MODEL_TYPE, String> valueProvider, final ImageResource icon, final String tooltip,
			final String actionLoadingLabel, final ListStore<MODEL_TYPE> listStore)
	{
		super(valueProvider, 30, "");

		final IconButtonCell cell = new ListStoreIconButtonCell<MODEL_TYPE>(icon, tooltip, listStore)
		{
			@Override
			protected void onClick(final MODEL_TYPE model, final int column, final int row, final String modelKey)
			{
				DkRunActionColumnConfig.this.onCellClick(model, column, row, modelKey, actionLoadingLabel);
			}

			@Override
			protected boolean isCellIconVisible(final MODEL_TYPE model, final int column, final int row, final String modelKey)
			{
				return super.isCellIconVisible(model, column, row, modelKey);
			}
		};
		setMenuDisabled(true);
		setResizable(false);
		setSortable(false);
		setFixed(true);
		setHideable(false);
		setGroupable(false);
		setCell(cell);
	}

	protected void onCellClick(final MODEL_TYPE model, final int column, final int row, final String modelKey, final String actionLoadingLabel)
	{
		if (runActionCondition(model))
		{
			new DkBaseAction<ACTION_RETURN_TYPE>(actionLoadingLabel)
			{
				@Override
				protected void run()
				{
					doRunAction(this, model, column, row, modelKey);
				}
			}.execute();
		}
	}

	protected abstract void doRunAction(DkBaseAction<ACTION_RETURN_TYPE> action, final MODEL_TYPE model, final int column, final int row, final String modelKey);

	protected boolean runActionCondition(final MODEL_TYPE model)
	{
		return true;
	}

	/**
	 *
	 * @param cell
	 * @param context
	 * @return whether the cell icon is visible
	 */
	protected boolean isCellIconVisible(final MODEL_TYPE model, final int column, final int row, final String modelKey)
	{
		return true;
	}
}
